var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hidden: true,
    tab: ["详情", "目录", "评价"], //tab标签
    current: 0, //tab切换变量
    //目录
    //评论
    pinglun: [],
    guanzhu: true, //视频关注
    qupinglun: true, //去评论
    plindex: false, //评论页面
    userInfo: {}, //获取头像和名称
    labelIndex: null, //单选框样式
    kc_id: '',
    goumai: false,
    vurl: "",
    toast: 0,
    autoplay: false,
    src: "", //音频路径
    poster: "", //音频封面图片
    zname: "你根本不懂", //音频路径音频名字
    author: "季彦霖", //音频作者名字
    Audiocurrent: "", //当前播放的是第几个音频
    loop: false,
    gaimusic: false, //修改audio；
    autoplay1: false,
    muvd: [],
    action: {
      method: ''
    }

  },
  /**
   * tab切换
   */
  musictoggle(e) {
    console.log(e)
    if (this.data.gaimusic == false) {
      const back = wx.getBackgroundAudioManager();
      back.src = e.currentTarget.dataset.src;
      console.log(back.src, e.currentTarget.dataset.src)
      back.title = e.currentTarget.dataset.title;
      back.coverImgUrl = e.currentTarget.dataset.pic;
      back.play();
      back.onPlay(() => {
        this.setData({
          gaimusic: true
        })
        console.log("音乐播放开始");
      })
      back.onPause(() => {
        console.log("暂停播放");
        this.setData({
          gaimusic: false
        })
      })
      back.onEnded(() => {
        console.log("音乐播放结束");
        this.setData({
          gaimusic: false
        })
      })
    } else {
      wx.pauseBackgroundAudio();
      this.setData({
        gaimusic: false
      })
    }
  },

  funplay: function(e) {
    console.log(e)
    var music = wx.getBackgroundAudioManager();
    music.src = e.target.dataset.src;
    music.play();
    // wx.playBackgroundAudio({
    //   dataUrl: e.target.dataset.src,
    //   title: '',
    //   coverImgUrl: ''
    // })
  },
  funpause: function() {
    var music = wx.getBackgroundAudioManager();
    music.pause();
  },





  audioPlay: function(e) {
    console.log(e)
    this.setData({
      action: {
        method: 'play'
      }
    })
  },

  tab: function(e) {
    var that = this;
    //console.log(e)
    var id = e.currentTarget.dataset.id
    app.util.request({
      'url': "entry/wxapp/Videoxianglist",
      data: {
        id: id
      },
      success: function(res) {
        //console.log(res)
        var demotimes = res.data.data;
        for (var i = 0; i < demotimes.length; i++) {
          var demotime = demotimes[i].demo;
          var m = parseInt(demotime / 60);
          var s = parseInt(demotime % 60);
          demotimes[i].demo = m + "分" + s + "秒";
        }
        var muvd = that.data.muvd
        //console.log(muvd)
        for (var j = 0; j < demotimes.length; j++) {
          muvd[j + 1] = demotimes[j]
        }


        //console.log(muvd)
        that.setData({
          muvd: muvd,
        })
      },
      fail: function(err) {
        console.log(err)
      },
    })



    that.setData({
      current: e.currentTarget.dataset.index,
      autoplay: false
    })
    // if (e.currentTarget.dataset.index == 1) {
    //   wx.showToast({
    //     title: '功能暂未开放',
    //   })
    // }
  },
  //播放
  suibian: function(e) {
    var that = this
    console.log(e)
    that.videoCtx = wx.createVideoContext('myVideo1')
    that.videoCtx1 = wx.createVideoContext('myVideo')
    this.setData({
      //Audiocurrent: e.currentTarget.dataset.index,
      hidden: false,
    })
    setTimeout(function() {
      that.videoCtx.play()
      that.videoCtx1.play()
    }, 500)
  },
  /**
   * 关注
   */

  // 点击关注
  likeClick: function(e) {
    var that = this;
    // 活动id
    var id = e.currentTarget.dataset.id
    console.log(e.currentTarget.dataset.id)
    var openid = wx.getStorageSync('openid');
    console.log(openid)
    // 判断活动是否收藏
    app.util.request({
      'url': 'entry/wxapp/CheckCollect',
      headers: {
        'Content-Type': 'application/json',
      },
      'cachetime': '0',
      data: {
        openid: openid,
        goods_id: id,
        cerated_type: 1
      },
      success: function(res) {
        console.log(res)
        if (res.data == 2) {
          console.log('已取消')
          app.util.request({
            'url': 'entry/wxapp/SaveCollect',
            'cachetime': '0',
            data: {
              openid: openid,
              goods_id: id,
              cerated_type: 1
            },
            dataType: 'json',
            success: function(res) {
              // console.log(res);
              wx.showToast({
                title: '取消成功',
                icon: 'none',
                duration: 1500,
              })
              that.setData({
                toast: 0
              })
            }
          })
        } else if (res.data == 1) {
          console.log('关注成功')
          app.util.request({
            'url': 'entry/wxapp/SaveCollect',
            headers: {
              'Content-Type': 'application/json',
            },
            'cachetime': '0',
            data: {
              openid: openid,
              goods_id: id,
              cerated_type: 1
            },
            dataType: 'json',
            success: function(res) {
              that.setData({
                collect_url: !that.data.collect_url,
                c_text: !that.data.c_text,
                toast: 1
              })
            }
          })
        }
      }
    })
  },
  /**
   * 视频目录
   */
  muurl: function(e) {
    var that = this
    var ystate = that.data.ystate
    if (that.data.goumai == false) {
      wx.showToast({
        title: '请先购买再观看',
        icon: 'none',
        duration: 3000
      })
    } else {
      var videoxiang = that.data.videoxiang
      var poster = e.currentTarget.dataset.pic;
      // that.audioCtx = wx.createAudioContext('myAudio')
      // that.audioCtx1 = wx.createAudioContext('myAudio1')
      var url = e.currentTarget.dataset.url;
      //console.log(url)
      var mp3 = e.currentTarget.dataset.data;
      // var surl = that.data.surl
      var sroomtitle = e.currentTarget.dataset.title;
      var room_teacher = e.currentTarget.dataset.name;
      var kaiguan = e.currentTarget.dataset.off;
      var Audiocurrent = e.currentTarget.dataset.index
      // console.log(current)
      if (e.currentTarget.dataset.off == 1) {
        const back = wx.getBackgroundAudioManager();
        console.log(e)
        back.src = mp3;
        // console.log(back.src, e.currentTarget.dataset.src)
        back.title = sroomtitle;
        back.coverImgUrl = poster;
        back.play();
        back.onPlay(() => {
          this.setData({
            gaimusic: true
          })
          //console.log("音乐播放开始");
        })
        back.onPause(() => {
          // console.log("暂停播放");
          this.setData({
            gaimusic: false
          })
        })
        back.onEnded(() => {
          // console.log("音乐播放结束");
          this.setData({
            gaimusic: false
          })
        })
      }

      that.setData({
        vurl: url,
        autoplay: false,
        room_teacher: room_teacher,
        sroomtitle: sroomtitle,
        kaiguan: kaiguan,
        Audiocurrent: Audiocurrent,
        mp3: mp3,
        loop: true,
        autoplay1: false,
        poster: poster,
        hidden: true,
      })
    }
    // setTimeout(function() {
    //   that.audioCtx.play()
    //   that.audioCtx1.play()
    // }, 500)
  },
  //开启下一个音频
  // nextPlay: function() {
  //   var that = this
  //   // that.audioCtx = wx.createAudioContext('myAudio')
  //   // that.audioCtx1 = wx.createAudioContext('myAudio1')

  //   var muvd = that.data.muvd
  //   console.log(muvd)
  //   var Audiocurrent = that.data.Audiocurrent
  //   Audiocurrent++
  //   var mp3 = muvd[Audiocurrent].mp3
  //   var url = muvd[Audiocurrent].room_video
  //   var room_teacher = muvd[Audiocurrent].name
  //   var sroomtitle = muvd[Audiocurrent].title
  //   var kaiguan = muvd[Audiocurrent].kaiguan;
  //   console.log(mp3)
  //   that.setData({
  //     mp3: mp3,
  //     autoplay: true,
  //     room_teacher: room_teacher,
  //     sroomtitle: sroomtitle,
  //     kaiguan: kaiguan,
  //     Audiocurrent: Audiocurrent,
  //   })
  //   // setTimeout(function() {
  //   //   that.audioCtx.play()
  //   //   that.audioCtx1.play()
  //   // }, 500)
  // },
  //视频
  // nextPlay1: function() {
  //   console.log(1)
  //   var that = this
  //   var muvd = that.data.muvd
  //   // that.videoCtx = wx.createVideoContext('myVideo1')
  //   // that.videoCtx1 = wx.createVideoContext('myVideo')
  //   console.log(muvd)
  //   var Audiocurrent = that.data.Audiocurrent
  //   Audiocurrent++
  //   // var mp3 = muvd[Audiocurrent].mp3
  //   if (Audiocurrent < muvd.length) {
  //     var url = muvd[Audiocurrent].room_video
  //     var room_teacher = muvd[Audiocurrent].name
  //     var sroomtitle = muvd[Audiocurrent].title
  //     var kaiguan = muvd[Audiocurrent].kaiguan;
  //     // console.log(mp3)
  //     that.setData({
  //       vurl: url,
  //       room_teacher: room_teacher,
  //       sroomtitle: sroomtitle,
  //       kaiguan: kaiguan,
  //       Audiocurrent: Audiocurrent,
  //       autoplay1: true
  //     })
  //     // setTimeout(function() {
  //     //   that.videoCtx.play()
  //     //   that.videoCtx1.play()
  //     // }, 500)
  //   } else {
  //     wx.showToast({
  //       title: '已学完全部章节',
  //     })
  //   }

  // },
  /**
   * 开始学习
   */
  xuexi: function() {
    this.setData({
      current: 1
    })
  },
  /***
   * 去评论
   */
  qupinglun: function(e) {
    //console.log(e)
    var that = this
    var s_id = e.currentTarget.dataset.data
    console.log(e)
    var openid = wx.getStorageSync('openid')
    app.util.request({
      'url': "entry/wxapp/Pingl",
      data: {
        s_id: s_id,
        openid: openid
      },
      success: function(res) {
        console.log(res)
        // console.log(m_openid)
        if (res.data.data == false) {
          wx.showToast({
            title: '您还未购买',
            icon: 'none',
            duration: 800,
          })
          return false;
        }
        if (res.data.data.m_comment !== '') {
          wx.showToast({
            title: '您已发表过评论',
            icon: 'none',
            duration: 1500,
          })
        } else {
          that.setData({
            qupinglun: false,
            plindex: true
          })
        }
      },
      fail: function(err) {
        console.log(err)
      },
    })
  },



  mqupinglun: function(e) {
    //console.log(e)
    var that = this
    var s_id = e.currentTarget.dataset.data
    console.log(s_id)
    var openid = wx.getStorageSync('openid')
    app.util.request({
      'url': "entry/wxapp/Pingl",
      data: {
        s_id: s_id,
        openid: openid
      },
      success: function(res) {
        console.log(res)
        if (res.data.data == false) {
          wx.showToast({
            title: '您未学习该课程',
            icon: 'success',
            duration: 800,
          })
        }
        if (res.data.data.m_comment !== '') {
          wx.showToast({
            title: '您已发表过评论',
            icon: 'success',
            duration: 1500,
          })
        } else {
          that.setData({
            qupinglun: false,
            plindex: true
          })
        }
      },
      fail: function(err) {
        console.log(err)
      },
    })
  },
  /**
   * 隐藏评论
   */
  close: function() {
    this.setData({
      plindex: false
    })
  },
  /**
   * 提交评论
   */
  formSubmit: function(e) {
    var that = this
    var count = e.detail.value
    let m_fenshu = that.data.labelIndex
    var s_id = count.s_id
    console.log(e)
    var m_comment = count.m_comment
    var m_money = count.room_money
    var openid = wx.getStorageSync('openid');
    console.log(m_money, m_comment, s_id, m_fenshu)
    if (m_fenshu == null) {
      wx.showToast({
        title: '请您评个花花吧^^',
        icon: 'success',
        duration: 1500,
      })
    } else {
      wx.showModal({
        title: '提示',
        content: ' 确认提交么？ ',
        success: function(res) {
          if (res.confirm) {
            var pinglun = that.data.pinglun;
            var date = new Date();
            var year = date.getUTCFullYear();
            var mouth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
            var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
            var time = year + "-" + mouth + "-" + day + " ";
            var obj = {};
            obj.m_img = that.data.userInfo.avatarUrl;
            obj.name = that.data.userInfo.nickName;
            obj.m_fenshu = e.detail.value.m_fenshu;
            obj.m_comment = e.detail.value.m_comment;
            obj.m_time = time;
            pinglun.unshift(obj);
            console.log(obj.m_img, obj.name)
            that.setData({
              pinglun: pinglun,
              plindex: false
            });
            app.util.request({
              'url': "entry/wxapp/Roomcoment",
              data: {
                name: that.data.userInfo.nickName,
                m_img: that.data.userInfo.avatarUrl,
                m_comment: m_comment,
                s_id: s_id,
                m_fenshu: m_fenshu,
                s_openid: openid,
              },
              success: function(res) {
                console.log(res)
              },
              fail: function(err) {
                console.log(err)
              },
            })
          }
        }
      })
    }
  },
  /**
   * 单选框样式改变
   */
  radioChange: function(e) {
    console.log(e.detail.value)
    this.setData({
      labelIndex: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var bgc = wx.getStorageSync('color')
    wx.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: bgc,
    })
    //console.log(options)
    var openid = wx.getStorageSync('openid')
    var sroomtitle = options.sroomtitle
    wx.setNavigationBarTitle({
        title: sroomtitle
      }),
      this.getBase();
    var that = this;
    app.util.request({
      'url': 'entry/wxapp/Scurl',
      success: function(res) {
        var surl = res.data.data
        that.setData({
          surl: surl
        })
      }
    })
    var userInfo = wx.getStorageSync('userInfo')
    var id = options.id
    that.setData({
      id: id,
      userInfo: userInfo
    })
    app.util.request({
      'url': "entry/wxapp/Videoxiang",
      data: {
        id: id,
        openid: openid
      },
      success: function(res) {
        //console.log(res)
        var demotimes = res.data.data;
        // for (var i = 0; i < demotimes.length; i++) {
        var demotime = demotimes.demo;
        var m = parseInt(demotime / 60);
        var s = parseInt(demotime % 60);
        demotimes.demo = m + "分" + s + "秒";
        // }
        if (demotimes.demo == "null") {
          demotimes.demo = ""
        }
        var muvd = that.data.muvd
        //console.log(muvd)
        muvd.unshift(demotimes)
        that.setData({
          muvd: muvd,
          videoxiang: res.data.data,
          kaiguan: res.data.data.kaiguan,
          mp3: res.data.data.mp3,
          room_money: res.data.data.room_money,
          vurl: res.data.data.room_video,
          sroomtitle: res.data.data.sroomtitle,
          room_teacher: res.data.data.room_teacher,
          poster: res.data.data.room_thumb
        })
      },
      fail: function(err) {
        console.log(err)
      },
    })

    app.util.request({
      'url': "entry/wxapp/Mianfei",
      data: {
        id: id,
        openid: openid
      },
      success: function(res) {
        // console.log(res)
        if (res.data.data.s_id) {
          var s_id = res.data.data.s_id
        } else {
          var s_id = ''
        }
        that.setData({
          baoming: res.data.data,
          openid: openid,
          s_id: s_id
        })
      },
      fail: function(err) {
        console.log(err)
      },
    })


    app.util.request({
      'url': "entry/wxapp/Allcoment",
      data: {
        id: id
      },
      success: function(res) {
        //console.log(res)
        that.setData({
          pinglun: res.data.data
        })
        // WxParse.wxParse('article', 'html', res.data.data.z_content, that, 5);
      },
      fail: function(err) {
        console.log(err)
      },
    })

    var openid = wx.getStorageSync('openid');
    app.util.request({
      'url': "entry/wxapp/Kcselect",
      data: {
        s_pid: id,
        s_openid: openid
      },
      success: function(res) {
        // console.log(res)
        that.setData({
          kcselect: res.data.data,
          //openid:openid
        })

        //console.log(wx.getStorageSync('openid'));
        var openids = wx.getStorageSync('openid');
        if ((res.data.data.s_openid) == openids) {
          that.setData({
            goumai: true
          })
        }
      },
      fail: function(err) {
        console.log(err)
      },
    })
    app.util.request({
      'url': 'entry/wxapp/CheckCollect',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        openid: openid,
        goods_id: id
      },
      success: function(res) {
        console.log(res.data)
        if (res.data == 2) {
          //console.log('已经关注')
          that.setData({
            toast: 1
          })
        } else if (res.data == 1) {
          console.log('关注')
          that.setData({
            // shoucang: '收藏',
            toast: 0,

          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

    this.getMygou()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function(e) {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.pauseBackgroundAudio();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //付费
  zhifu: function(e) {
    var that = this;
    let room_money = that.data.room_money
    var id = that.data.id
    var name = e.currentTarget.dataset.name
    var openid = wx.getStorageSync('openid');
    if (room_money <= 0) {
      console.log('免费')
      app.util.request({
        'url': "entry/wxapp/Kcinsert",
        data: {
          s_ormoney: room_money,
          s_pid: id,
          s_openid: openid,
          m_type: 1,
          s_type: 0,
          m_tj: 0
        },
        success: function(res) {
          console.log(res)
          that.setData({
            openid: openid,
            ystate: 1,
            goumai: true
          })
        },

      })
      that.setData({
        current: 1
      })
    } else {
      console.log("付费")
      wx.showModal({
        title: '是否支付',
        success: function(res) {
          if (res.confirm) {

            app.util.request({
              'url': 'entry/wxapp/Orderpay',
              method: "GET",
              data: {
                s_openid: openid,
                s_ormoney: room_money
              },
              success: function(res) {
                wx.requestPayment({
                  'timeStamp': res.data.timeStamp,
                  'nonceStr': res.data.nonceStr, //字符串随机数
                  'package': res.data.package,
                  'signType': res.data.signType,
                  'paySign': res.data.paySign,
                  success: function(res) {
                    app.util.request({
                      'url': "entry/wxapp/Joninmoney",
                      data: {
                        use_openid: openid,
                        leixing: '课堂',
                        name: name,
                        pay: room_money
                      },
                      header: {
                        'content-type': 'application/json'
                      },
                      success: function(res) {
                        console.log(res)

                      },
                      fail: function(err) {
                        console.log(err)
                      },
                    })
                    app.util.request({
                      'url': "entry/wxapp/Kcinsert",
                      data: {
                        s_ormoney: room_money,
                        s_pid: id,
                        s_openid: openid,
                        m_type: 1,
                        s_type: 1,
                        m_tj: 0
                      },
                      success: function(res) {
                        console.log(res)
                        that.setData({
                          goumai: true,
                          s_id: res.data.data
                        })
                      },

                    })

                  },
                  fail: function(error) {
                    console.log(error);
                  },
                })
              }
            })
          }
        },
        fail: function(res) {
          that.setData({
            goumai: false
          })
        },
      })

    }
  },
  //轮播图
  getBase: function() {
    var that = this;
    //console.log(app);
    app.util.request({
      'url': 'entry/wxapp/Base',
      success: function(res) {
        //console.log(res)
        that.setData({
          bq_thumb: res.data.data.bq_thumb,
          bq_name: res.data.data.bq_name
        })
        // wx.setNavigationBarTitle({ title: that.data.baseinfo.show_title });
      },
      fail: function(err) {
        console.log(err)
      },

    })
  },
  //查询一条我是否购买的记录
  getMygou: function() {
    var that = this;
    var id = that.data.id
    var openid = wx.getStorageSync('openid')
    app.util.request({
      'url': "entry/wxapp/Mygou",
      data: {
        id: id,
        openid: openid
      },
      success: function(res) {
        //console.log(res)
        if (res.data.data.s_id) {
          var s_id = res.data.data.s_id
        } else {
          var s_id = ''
        }
        that.setData({
          s_id: s_id
        })
      },
      fail: function(err) {
        console.log(err)
      },
    })
  }
})